package org.example.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg1 {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection();){
            Scanner scanner= new Scanner(System.in);
            System.out.println("请输入用户名");
            String username = scanner.nextLine();
            System.out.println("请输入密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称：");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄：");
            int age = scanner.nextInt();
            String sql1 ="SELECT id FROM user WHERE username=?";
            PreparedStatement prt1 = connection.prepareStatement(sql1);
            prt1.setString(1,username);
            ResultSet rs = prt1.executeQuery();
            if (rs.next()){
                System.out.println("用户名已使用，请重新输入");
            }else {
                String sql2= ("INSERT INTO user(username,password,nickname,age)VALUES(?,?,?,?)");
                PreparedStatement prt2 = connection.prepareStatement(sql2);
                prt2.setString(1,username);
                prt2.setString(2,password);
                prt2.setString(3,nickname);
                prt2.setInt(4,age);
                prt2.executeUpdate();
                System.out.println("注册成功，请重新登录！");
            }
        } catch (SQLException e) {
           e.printStackTrace();
        }

    }
}
